package com.yzy.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.yzy.model.ColumnClass;

import freemarker.template.Template;

public class CodeGenerateUtils {
	 private final String AUTHOR = "yzy";
	    private final String CURRENT_DATE = "2018/06/06";
	    private final String tableName = "tm_fleet_info_feed_back";
	    private final String id = "back_id";
	    private final String packageName = "com.yonyou.dcs.marketSupport";
	    private final String tableAnnotation = "大客户反馈信息";
	    private final String URL = "jdbc:mysql://172.20.32.183:3309/market_support?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true";
	    private final String USER = "dbadmin";
	    private final String PASSWORD = "Root-1234";
	    private final String DRIVER = "com.mysql.jdbc.Driver";
	    private final String diskPath = "D://";
	    private final String changeTableName = replaceUnderLineAndUpperCase(tableName);

	    public Connection getConnection() throws Exception{
	        Class.forName(DRIVER);
	        Connection connection= DriverManager.getConnection(URL, USER, PASSWORD);
	        return connection;
	    }

	    public static void main(String[] args) throws Exception{
	        CodeGenerateUtils codeGenerateUtils = new CodeGenerateUtils();
	        codeGenerateUtils.generate();
	    }

	    public void generate() throws Exception{
	        try {
	            Connection connection = getConnection();
	            DatabaseMetaData databaseMetaData = connection.getMetaData();
	            ResultSet resultSet = databaseMetaData.getColumns(null,"%", tableName,"%");
	            //生成mapper
	          //  generateMapperFile(resultSet);
	            //生成dao
	             generateDaoFile(resultSet);
	            //生成Repository
	        //    generateRepositoryFile(resultSet);
	            //生成ServiceInterface
	            generateServiceInterfaceFile(resultSet);
	            //生成ServiceImpl
	            generateServiceImplFile(resultSet);
	            //生成Controller
	            generateControllerFile(resultSet);
	            //生成DTO
	            generateDTOFile(resultSet);

	            //生成po
	            generatePOFile(resultSet);
	            
	            //生成mapper
	        //    generateModelFile(resultSet);
	        } catch (Exception e) {
	            throw new RuntimeException(e);
	        }finally{

	        }
	    }

	    private void generateModelFile(ResultSet resultSet) throws Exception{

	        final String suffix = ".java";
	        final String path = diskPath + changeTableName + suffix;
	        final String templateName = "Model.ftl";
	        File mapperFile = new File(path);
	        List<ColumnClass> columnClassList = new ArrayList<>();
	        ColumnClass columnClass = null;
	        while(resultSet.next()){
	            //id瀛楁鐣ヨ繃
	            if(resultSet.getString("COLUMN_NAME").equals("id")) continue;
	            columnClass = new ColumnClass();
	            //鑾峰彇瀛楁鍚嶇О
	            columnClass.setColumnName(resultSet.getString("COLUMN_NAME"));
	            //鑾峰彇瀛楁绫诲瀷
	            columnClass.setColumnType(resultSet.getString("TYPE_NAME"));
	            //杞崲瀛楁鍚嶇О锛屽 sys_name 鍙樻垚 SysName
	            columnClass.setChangeColumnName(replaceUnderLineAndUpperCase(resultSet.getString("COLUMN_NAME")));
	            //瀛楁鍦ㄦ暟鎹簱鐨勬敞閲�
	            columnClass.setColumnComment(resultSet.getString("REMARKS"));
	            columnClassList.add(columnClass);
	        }
	        Map<String,Object> dataMap = new HashMap<>();
	        dataMap.put("model_column",columnClassList);
	        generateFileByTemplate(templateName,mapperFile,dataMap);

	    }

	    private void generateDTOFile(ResultSet resultSet) throws Exception{
	        final String suffix = "DTO.java";
	        final String path = diskPath + changeTableName + suffix;
	        final String templateName = "DTO.ftl";
	        File mapperFile = new File(path);
	        Map<String,Object> dataMap = new HashMap<>();
	        generateFileByTemplate(templateName,mapperFile,dataMap);
	    }

	    private void generatePOFile(ResultSet resultSet) throws Exception{
	        final String suffix = "Po.java";
	        final String path = diskPath + changeTableName + suffix;
	        final String templateName = "PO.ftl";
	        File mapperFile = new File(path);
	        Map<String,Object> dataMap = new HashMap<>();
	        generateFileByTemplate(templateName,mapperFile,dataMap);
	    }
	    
	    private void generateControllerFile(ResultSet resultSet) throws Exception{
	        final String suffix = ".java";
	        final String path = diskPath + changeTableName + suffix;
	        final String templateName = "Controller.ftl";
	        File mapperFile = new File(path);
	        Map<String,Object> dataMap = new HashMap<>();
	        generateFileByTemplate(templateName,mapperFile,dataMap);
	    }

	    private void generateServiceImplFile(ResultSet resultSet) throws Exception{
	        final String suffix = "Impl.java";
	        final String path = diskPath + changeTableName + suffix;
	        final String templateName = "ServiceImpl.ftl";
	        File mapperFile = new File(path);
	        Map<String,Object> dataMap = new HashMap<>();
	        generateFileByTemplate(templateName,mapperFile,dataMap);
	    }

	    private void generateServiceInterfaceFile(ResultSet resultSet) throws Exception{
	        final String prefix = "I";
	        final String suffix = "Service.java";
	        final String path = diskPath + prefix + changeTableName + suffix;
	        final String templateName = "ServiceInterface.ftl";
	        File mapperFile = new File(path);
	        Map<String,Object> dataMap = new HashMap<>();
	        generateFileByTemplate(templateName,mapperFile,dataMap);
	    }

	    private void generateRepositoryFile(ResultSet resultSet) throws Exception{
	        final String suffix = "Repository.java";
	        final String path = diskPath + changeTableName + suffix;
	        final String templateName = "Repository.ftl";
	        File mapperFile = new File(path);
	        Map<String,Object> dataMap = new HashMap<>();
	        generateFileByTemplate(templateName,mapperFile,dataMap);
	    }

	    private void generateDaoFile(ResultSet resultSet) throws Exception{
	        final String suffix = "Dao.java";
	        final String path = diskPath + changeTableName + suffix;
	        final String templateName = "DAO.ftl";
	        File mapperFile = new File(path);
	        Map<String,Object> dataMap = new HashMap<>();
	        generateFileByTemplate(templateName,mapperFile,dataMap);

	    }

	    private void generateMapperFile(ResultSet resultSet) throws Exception{
	        final String suffix = "Mapper.xml";
	        final String path = diskPath + changeTableName + suffix;
	        final String templateName = "Mappter.ftl";
	        File mapperFile = new File(path);
	        Map<String,Object> dataMap = new HashMap<>();
	        generateFileByTemplate(templateName,mapperFile,dataMap);

	    }

	    private void generateFileByTemplate(final String templateName,File file,Map<String,Object> dataMap) throws Exception{
	        Template template = FreeMarkerTemplateUtils.getTemplate(templateName);
	        FileOutputStream fos = new FileOutputStream(file);
	        dataMap.put("table_name_small",tableName);
	        dataMap.put("table_name",changeTableName);
	        dataMap.put("id",id);
	        dataMap.put("author",AUTHOR);
	        dataMap.put("date",CURRENT_DATE);
	        dataMap.put("package_name",packageName);
	        dataMap.put("table_annotation",tableAnnotation);
	        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240);
	        template.process(dataMap,out);
	    }

	    public String replaceUnderLineAndUpperCase(String str){
	        StringBuffer sb = new StringBuffer();
	        sb.append(str);
	        int count = sb.indexOf("_");
	        while(count!=0){
	            int num = sb.indexOf("_",count);
	            count = num + 1;
	            if(num != -1){
	                char ss = sb.charAt(count);
	                char ia = (char) (ss - 32);
	                sb.replace(count , count + 1,ia + "");
	            }
	        }
	        String result = sb.toString().replaceAll("_","");
	        return StringUtils.capitalize(result);
	    }
}
